<?php

namespace App\Http\Controllers\Client\Course;

use App\Http\Controllers\ClientController;
use App\Models\Tools\AliOss;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CourseStoreController extends ClientController
{

    /**
     * 课程列表接口(包含vip的信息)
     */
    public function index()
    {
        $we_id = $this->we_id;
        try {
            // 查询会员信息
//            $vip_message = self::vipMessage($we_id);
            // 查询课程信息
            $course_message = self::courseMessage($we_id);

            $is_business = DB::table('shop')
                ->where('we_id','=',$we_id)
                ->where('verified','=',1)
                ->count();

//            return $this->setReturnJson(0, 'success', ['vip_message' => $vip_message, 'course_message' => $course_message]);
            return $this->setReturnJson(0, 'success', ['course_message'=>$course_message,'is_business'=>$is_business && true]);
        } catch (\Exception $e) {
            Log::emergency(CourseStoreController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1,'课程查询失败');
        }
    }

    /**
     * 查询会员信息
     * @param $we_id
     * @return array
     */
    public static function vipMessage($we_id)
    {
        //如果不是会员，查询会员商品
        $vip_message = DB::table('laifei_sys_vip')->select()->get()->all();
        //当前用户是否是会员
        $vip = DB::table('laifei_vip')
            ->where('we_id','=',$we_id)
            ->pluck('vip_id')
            ->toArray();
        return ['vip_message' => $vip_message, 'vip' => $vip];
    }

    /**
     * 查询课程信息
     * @param $we_id
     * @return array
     */
    public static function courseMessage($we_id)
    {
        // 查询当前用户是否已购买课程
        $bought = DB::table('laifei_course')
            ->where('we_id','=',$we_id)
            ->pluck('course_id')
            ->toArray();
        // 判断当前用户是否是黑卡会员(高级)，如果是，打85折
        $is_vip = DB::table('laifei_vip')
            ->where('we_id','=',$we_id)
            ->where('end_time','>',date('Y-m-d H:i:s'))
            ->where('vip_id','=',2)
            ->count();

        // 查询课程信息
        $courses = DB::table('laifei_sys_course')
            ->get()
            ->map(function ($item) use ($bought,$is_vip) {
                if(in_array($item->course_id,$bought)){
                    $item->bought = true;
                }
                if($is_vip){
                    $item->price = ceil($item->price * 100 * 0.85) / 100.00;
                }
                $item->price_before = number_format($item->price_before,2);
                $item->price = number_format($item->price,2);
                $item->title_img = AliOss::getUrl($item->title_img);
                return $item;
            })
            ->all();
        return $courses;
    }

}
